package rt.wxf_bo.service.impl;

import io.minio.BucketExistsArgs;
import io.minio.MinioClient;
import org.jodconverter.core.DocumentConverter;
import org.jodconverter.core.office.OfficeException;
import org.jodconverter.local.LocalConverter;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

@Service
public class FileConversionService {

    /**
     * 将文件转换为 PDF
     *
     * @param file 上传的文件
     * @return 转换后的 PDF 文件
     * @throws IOException      如果文件读写失败
     * @throws OfficeException 如果 LibreOffice 转换失败
     */
    public File convertToPdf(MultipartFile file) throws IOException, OfficeException {
        // 将上传的文件保存到临时目录
        Path tempFile = Files.createTempFile("temp-", file.getOriginalFilename());
        Files.copy(file.getInputStream(), tempFile, StandardCopyOption.REPLACE_EXISTING);

        // 定义输出文件路径
        File outputFile = File.createTempFile("output-", ".pdf");

        // 使用 LibreOffice 进行转换
        DocumentConverter converter = LocalConverter.builder().build();
        converter.convert(tempFile.toFile()).to(outputFile).execute();

        // 删除临时文件
        Files.deleteIfExists(tempFile);

        return outputFile;
    }

    public static void main(String[] args) {
    try {
        MinioClient minioClient = MinioClient.builder()
                .endpoint("http://101.43.151.37:9000")
                .credentials("rtminio", "sdrt@6177155")
                .build();

        boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket("allfile").build());
        System.out.println("Bucket exists: " + found);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}